/**
 *
 *  Request Wrapper Function
 *  @params callAPI obj
 *
		{
			method: 'GET',    // (required) GET, POST, PUT, DELETE...
			url: '',	      // (required) api url
			query: ''		  // (optional) query url string
			data: null,		  // (optional) post form data
			accept: '',       // (optional) default = json
			success_msg: '',  // (optional) if set, show alert when success
			failure_msg: '',  // (optional) if set, show alert when fail
			success_fn: null, // (optional) success callback function (input: res.body.result)
			failure_fn: null  // (optional) fail callback function (input: res.body or pure err)
		}
 *
 */
import request from "superagent";
import { getJWS } from "./storage";
import { setAuthority } from "../utils/authority";

function isDev() {
  return window.location.hostname === "localhost";
}
function getUrl(url) {
  let newUrl = "";
  if (isDev()) {
    // CORS hack
    if (url.indexOf("http") === -1) {
      // relative path
      newUrl = "http://" + window.location.hostname + "/api/" + url;
    }
  } else {
    // newUrl = 'https://'+location.hostname+':8081/service/'+url;
    //newUrl = 'https://archiver-back-end:8080/service/'+url;
    newUrl = "/api/" + url;
  }
  return newUrl;
}

// general rest task (No Locale)
export default function restRequest(callAPI) {
  if (typeof callAPI === "undefined") {
    return;
  }
  // optional
  let {
    accept,
    data,
    query,
    success_msg,
    failure_msg,
    success_fn,
    failure_fn,
    isFullPath
  } = callAPI;
  //accept = accept ? accept : 'application/json';

  // required
  const { method, url } = callAPI;
  // console.debug('url', url);
  // check
  if (typeof method !== "string") {
    throw new Error("Specify a valid method.");
  }
  if (typeof url !== "string") {
    throw new Error("Specify a string endpoint URL.");
  }

  if (
    (success_fn && typeof success_fn !== "function") ||
    (failure_fn && typeof failure_fn !== "function")
  ) {
    throw new Error("Specify a valid callback function.");
  }

  if (
    (success_msg && typeof success_msg !== "string") ||
    (failure_msg && typeof failure_msg !== "string")
  ) {
    throw new Error("Specify a valid string msg.");
  }

  const isFull = isFullPath ? isFullPath : false;

  var req = request(method, isFull ? url : getUrl(url));

  if ("function" === typeof data) data = null;
  if ("function" === typeof query) query = null;
  // deal with CORS
  req.withCredentials();
  if (getJWS()) {
    req.auth(getJWS(), { type: "bearer" });
  }

  if (data) {
    req.send(data);
  }

  req.accept(accept ? accept : "json"); // default: json

  req.end(function(err, res) {
    if (err) {
      // console.debug('fail', err, res);
      let errorResp = { message: "", responseCode: "" };
      if (res) {
        if (res.status === 401) {
          setAuthority("");
          location.reload();
        } else if (res.status === 404) {
          //TODO: confirm other api failuer status
          console.log("error : 404");
          errorResp = {
            responseCode: "TryAgainLater",
            message: res.statusText
          };
        } else {
          // not network error
          errorResp = res.body ? res.body : JSON.parse(res.text);
        }
      }

      if (failure_fn) {
        failure_fn(err, errorResp);
      }
    } else {
      if (success_fn) {
        success_fn(res.body);
      }
    }
  });

  return req;
}
